package com.stu.wgt.test.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.Pet;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.service.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/pet")
public class PetController {
    @Autowired
    PetService petService;

    @PostMapping("/add")
    public R addPet(@RequestBody Pet pet) {
        int result = petService.insert(pet);
        if (result == 1) {
            return R.ok().data("msg", "添加成功");
        }
        return R.error().data("msg", "添加失败");
    }

    @DeleteMapping("/delete/{id}")
    public R deletePet(@PathVariable("id") Integer id) {
        int result = petService.delete(id);
        if (result == 1) {
            return R.ok().data("msg", "删除成功");
        }
        return R.error().data("msg", "删除失败");
    }

    @PutMapping("/update/{id}")
    public R updatePet(@PathVariable("id") Integer id, @RequestBody Pet pet) {
        pet.setId(id);
        int result = petService.update(pet);
        if (result == 1) {
            return R.ok().data("msg", "更新成功");
        }
        return R.error().data("msg", "更新失败");
    }

    @GetMapping("/selectById/{id}")
    public R selectById(@PathVariable("id") Integer id) {
        try {
            List<Pet> petList = petService.selectById(id);
            return R.ok().data("pet", petList);
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

    @GetMapping("/search")
    public R searchPet(@RequestParam("query") String query,
                       @RequestParam("pagenum") int pageNum,
                       @RequestParam("pagesize") int pageSize) {
        try {
            IPage<Pet> petList = petService.searchPet(query, pageNum, pageSize);
            return R.ok().data("pet", petList.getRecords()).data("total", petList.getTotal());
        } catch (Exception e) {
            return R.error().data("msg", "查询失败，请更新查询参数");
        }
    }

    /**
     * 宠物图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        System.out.println("上传文件");
        try {
            String uploadDir = "E:/桌面/毕业设计/代码/后端/src/main/resources/static/image/";
            String originalFileName = file.getOriginalFilename();
            String fileExtension = "";

            // 获取文件后缀（扩展名）
            if (originalFileName != null && originalFileName.lastIndexOf(".") != -1) {
                fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");//UUID生成不重复的一串数字
            String newFileName = uuid + fileExtension; // 新的文件名 = UUID + 文件扩展名

            File dest = new File(uploadDir + newFileName);
            file.transferTo(dest);

            String tmpPath = newFileName;
            String url = "http://127.0.0.1:8888/image/" + tmpPath;
            return R.ok().data("tmp_path", tmpPath).data("url", url);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

}

